﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.PhilChuang.Mobile.Apps.LocationSender.Model.Data;
using Com.PhilChuang.Mobile.Apps.LocationSender.Ui.Views;
using Com.PhilChuang.Pmvp.Utils;
using Com.PhilChuang.Utils;

namespace Com.PhilChuang.Mobile.Apps.LocationSender.Ui.Presenters
{
	public class SettingsPresenter : AbstractLocationSenderAppPresenter<ISettingsView>
	{
		#region Constants (EMPTY)
		#endregion

		#region Private members
		private LocationSenderSettings m_Settings;
		#endregion

		#region Constructors / Dispose
		public SettingsPresenter () : this (AppServiceLocator.Instance.GetImpl<ISettingsView> ())
		{
		}

		public SettingsPresenter (ISettingsView view) : base (view)
		{
		}
		#endregion

		#region AbstractPresenter implementation
		/// <summary>
		/// Subscribe to View events after the View is registered during Presenter instantiation.
		/// Call base impl as the first step.
		/// </summary>
		protected override void SubscribeToViewEvents ()
		{
			base.SubscribeToViewEvents ();

			View.DoDisableLocationServices += OnDoDisableLocationServices;
		}

		/// <summary>
		/// Unsubscribes to View events after the View has Closed.
		/// Call base impl as the first step.
		/// </summary>
		protected override void UnsubscribeFromViewEvents ()
		{
			base.UnsubscribeFromViewEvents ();

			View.DoDisableLocationServices -= OnDoDisableLocationServices;
		}

		protected override void RefreshData ()
		{
			base.RefreshData ();

			m_Settings = App.Settings;
		}

		/// <summary>
		/// Updates the View with Presenter data.
		/// Call base impl as the last step.
		/// </summary>
		protected override void UpdateToView ()
		{
			base.UpdateToView ();
		}

		protected override void UpdateFromView ()
		{
			base.UpdateFromView ();
		}

		/// <summary>
		/// Fires when the View is trying to Close.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected override void OnDoClose (object sender, System.ComponentModel.CancelEventArgs e)
		{
			// if we're here, we're navigating backwards
			App.SaveSettings ();
		}
		#endregion

		#region Event handlers
		private void OnDoDisableLocationServices ()
		{
			if (View.DisplayYesNoChoice ("Access to Location Services is necessary for the app to function, so if it is disabled then the app will close. Is this ok?", "Confirm"))
			{
				m_Settings.UserApprovedLocationServices = false;
				UpdateFromView ();
				App.SaveSettings ();
				View.DisplayMessage ("Location Services disabled, closing application...", "Disabled");
				AppServiceLocator.Instance.GetImpl<IAppHelper> ().ForceExit ();
			}
		}
		#endregion
	}
}
